// import { WHITE_LIST } from './config'
import store from '@/store'
import { req } from './request'

// 请求之前拦截
req.defaultReq.beforeSend = res => {
	// value为对象
	if (typeof res.data == 'object') {
		Object.keys(res.data).map(item => {
			if (res.data[item] === '' || res.data[item] === null || `${res.data[item]}` == 'undefined') {
				delete res.data[item]
			}
			return res
		})
	}
	return res
}

// 请求完成之前
req.defaultReq.beforeFinish = res => {
	return res.data
}

// 全局错误拦截
req.defaultReq.errorHandler = (err, next) => {
	next(err)
}

function requestOption(options) {
	return {
		...options,
		header: {
			...(options.header || {}),
			...req.defaultReq.header,
			Authorization: `Bearer ${store.user.userData.access_token}`
		},
		abortFun: () => {
			// const urls = info.url.split('?')
			// 过滤白名单接口
			// if (WHITE_LIST.indexOf(urls[0]) === -1) {
			// 	// 未授权终止请求
			// 	if (!store.user.userData.access_token) {
			// 		bt.abort()
			// 	}
			// }
		}
	}
}

export default {
	get(path, data = '', options = {}) {
		return req.ajax(
			requestOption({
				...options,
				type: 'GET',
				path,
				data
			})
		)
	},
	put(path, data, options = {}) {
		return req.ajax(
			requestOption({
				path,
				data,
				type: 'PUT',
				title: '加载中...',
				...options
			})
		)
	},
	post(path, data, options = {}) {
		return req.ajax(
			requestOption({
				path,
				data,
				type: 'POST',
				title: '加载中...',
				...options
			})
		)
	},
	deleted(path, data, options = {}) {
		return req.ajax(
			requestOption({
				path,
				data,
				type: 'DELETE',
				title: '加载中...',
				...options
			})
		)
	}
}
